import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/util/http'
import createPersistedState from "vuex-persistedstate";  // 持久化存储

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState({
    reducer: (store) => {
      return {
        cityId: store.cityId,
        cityName: store.cityName
      }
    }
  })],  // 指定将id和城市名存储到本地储存中
  // 公共状态state
  state: {
    isShow: true,
    footHight: 40,
    cinemaBarHight: 46,
    cityId: '440300',
    cityName: '深圳',
    cityList: [],
    cinemaList: [],
  },
  getters: {
  },
  // 统一管理，被devtools 记录状态的修改
  // 只能支持同步
  mutations: {
    changeShow (state, show) {
      state.isShow = show;
    },
    changeCity (state, city) {
      state.cityName = city.name
      state.cityId = city.cityId
    },
    changeCityList (state, cityList) {
      state.cityList = cityList;
    },
    changeCinemaList (state, cinemaList) {
      state.cinemaList = cinemaList
    },
    // 清空
    clearAll (state) {
      state.cinemaList = []
    }
  },
  // 支持异步和同步
  actions: {
    getCinemaList (store) {
      return http({
        url: `/gateway?cityId=${store.state.cityId}&ticketFlag=1&k=2467650`,
        headers: {
          'X-Host': 'mall.film-ticket.cinema.list'
        }
      }).then(res => {
        // console.log(res.data.data.cinemas);
        store.commit('changeCinemaList', res.data.data.cinemas)
      })
    },
  },
  modules: {
  }
})

// 注意事项：
// vuex 默认是管理里在内存，一刷新页面，公共状态就丢失
// vuex 持久化问题

// vuex在项目中的作用
// 1.非父子通信
// 2.后端数据缓存快照，减少重复数据请求，减轻服务器压力，提高用户体验--异步数据管理
